package cc.rengu.igas.opms.core.service.trans.common;

import cc.rengu.igas.opms.common.constant.OpmsParamConstant;
import cc.rengu.igas.opms.common.enums.RespCodeEnum;
import cc.rengu.igas.opms.common.util.ImageUtil;
import cc.rengu.igas.opms.core.service.base.ManageService;
import cc.rengu.igas.opms.facade.bean.AdInfo;
import cc.rengu.igas.opms.facade.request.AdInfoQueryRequest;
import cc.rengu.igas.opms.facade.response.AdInfoQueryResponse;
import cc.rengu.igas.share.core.model.MarketingAdsInfo;
import cc.rengu.igas.share.core.realize.BompService;
import cc.rengu.igas.share.core.realize.impl.BompServiceImpl;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.dao.SysParamMapper;
import cc.rengu.oltp.service.common.dao.impl.SysParamMapperImpl;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.StringUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 营销广告信息查询服务
 *
 * @author keyi
 * @modify by wangcheng
 * @date 2020/4/1.
 */
public class AdInfoQueryService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        AdInfoQueryRequest adInfoQueryRequest = new AdInfoQueryRequest();
        ConvertUtil.convertOutput(adInfoQueryRequest);
        return adInfoQueryRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {

        AdInfoQueryRequest adInfoQueryRequest = (AdInfoQueryRequest) request;
        AdInfoQueryResponse adInfoQueryResponse = new AdInfoQueryResponse();

        //获取营销管理信息
        BompService bompService = new BompServiceImpl();
        List<MarketingAdsInfo> marketingAdsInfoList = bompService.getMarketingAdsInfo(adInfoQueryRequest.getHeader().getInstId(), adInfoQueryRequest.getAdType());
        if (null != marketingAdsInfoList && !marketingAdsInfoList.isEmpty()) {
            ArrayList<AdInfo> adInfoList = new ArrayList<>();
            for (MarketingAdsInfo marketingAdsInfo : marketingAdsInfoList) {
                //判断当前广告数据的状态：01-正式，02-停用，03-已注销
                if (!"01".equals(marketingAdsInfo.getStatus())) {
                    rglog.debug("该营销广告数据非正式数据:<{}>", JSON.toJSONString(marketingAdsInfo));
                    continue;
                }
                //校验当前广告的是否可用，是否在生效时间段内
                if (!checkAdInfoIsAvailable(marketingAdsInfo)) {
                    continue;
                }
                AdInfo adInfo = new AdInfo();
                //获取图片信息，如果有缩略图则取缩略图 若没有则取本地图片再进行压缩
                if (StringUtil.isEmptyOrNull(marketingAdsInfo.getThumbnailPath())) {
                    adInfo.setAdImageUrl(downImage(adInfoQueryRequest.getHeader().getInstId(), marketingAdsInfo.getImageLocalPath()));
                } else {
                    adInfo.setAdImageUrl(downImage(adInfoQueryRequest.getHeader().getInstId(), marketingAdsInfo.getThumbnailPath()));
                }
                adInfo.setAdDesc(marketingAdsInfo.getAdDesc());
                adInfo.setPushAdModule(marketingAdsInfo.getPushAdModule());
                adInfo.setImageIndex(marketingAdsInfo.getImageIndex());
                adInfo.setAdUrl(marketingAdsInfo.getMarketingPagePath());
                adInfoList.add(adInfo);
            }
            adInfoQueryResponse.setAdInfoList(adInfoList);
        }
        //设置应答
        BizResponse<AdInfoQueryResponse> bizResponse = new BizResponse<>();
        bizResponse.setResult(adInfoQueryResponse);
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        AdInfoQueryResponse adInfoQueryResponse = (AdInfoQueryResponse) bizResponse.getResult();
        ConvertUtil.convertInput(adInfoQueryResponse);
    }

    /**
     * 获取二维码图片信息内容
     *
     * @param instId   法人机构号
     * @param dsLogUrl 营销广告地址
     * @return 图片内容压缩
     * @throws Exception 异常
     */
    private String downImage(String instId, String dsLogUrl) throws Exception {

        SysParamMapper sysParamMapper = new SysParamMapperImpl();
        SysParam localUrlPrefix = sysParamMapper.selectSysParamByPrimaryKey(instId, OpmsParamConstant.IMAGE_STORAGE_PARAM_TYPE, OpmsParamConstant.LOCAL_IMAGE_STORAGE_PATH);
        if (null == localUrlPrefix) {
            rglog.error("查询系统参数表，根据机构获取图片存储服务器路径为空！InstId：<{}>!", instId);
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }

        //共享文件夹路径
        String shareUrl;
        if (localUrlPrefix.getParamValue().trim().endsWith("/")) {
            shareUrl = localUrlPrefix.getParamValue().trim();
        } else {
            shareUrl = localUrlPrefix.getParamValue().trim() + "/";
        }

        //文件存储的全路径
        String fileFullPath = shareUrl + dsLogUrl;
        rglog.info("营销广告图片全路径:<{}>", fileFullPath);

        //读取文件内容
        File downloadFile = new File(fileFullPath);
        if (!downloadFile.exists()) {
            rglog.error("文件<{}>不存在!", fileFullPath);
            return "";
        }
        FileInputStream fileInputStream = null;
        byte[] downloadFileBytes;
        try {
            fileInputStream = new FileInputStream(downloadFile);
            downloadFileBytes = new byte[fileInputStream.available()];
            fileInputStream.read(downloadFileBytes);
            fileInputStream.close();
        } finally {
            if (null != fileInputStream) {
                fileInputStream.close();
            }
        }
        //压缩图片
        byte[] commpressImageData = ImageUtil.commpressPicForScale(downloadFileBytes, 20, 0.4);
        rglog.debug("压缩图片后的大小:<{}>", commpressImageData.length);

        //base64解压
        return Base64.encodeBase64String(commpressImageData);
    }

    /**
     * 检查当前广告是否在有效期内
     * 生效日期为空表示发布即生效；失效日期为空表示永不过期
     *
     * @param marketingAdsInfo 营销广告信息
     * @return 广告是否可用
     */
    private boolean checkAdInfoIsAvailable(MarketingAdsInfo marketingAdsInfo) {
        rglog.debug("当前营销广告生效日期:<{}>,失效日期:<{}>", marketingAdsInfo.getBeginTime(), marketingAdsInfo.getExpireTime());
        if (StringUtil.isEmptyOrNull(marketingAdsInfo.getBeginTime()) && StringUtil.isEmptyOrNull(marketingAdsInfo.getExpireTime())) {
            rglog.debug("生效日期和失效日期都为空，当前营销广告有效");
            return true;
        } else if (StringUtil.isEmptyOrNull(marketingAdsInfo.getBeginTime()) && !StringUtil.isEmptyOrNull(marketingAdsInfo.getExpireTime())) {
            String currentDate = DateUtil.getCurrentDate();
            rglog.debug("生效日期为空，失效日期不为空，校验当前日期:<{}>是否小于失效日期:<{}>", currentDate, marketingAdsInfo.getExpireTime());
            return DateUtil.compareDate(currentDate, marketingAdsInfo.getExpireTime()) <= 0;
        } else if (!StringUtil.isEmptyOrNull(marketingAdsInfo.getBeginTime()) && StringUtil.isEmptyOrNull(marketingAdsInfo.getExpireTime())) {
            String currentDate = DateUtil.getCurrentDate();
            rglog.debug("生效日期不为空，失效日期为空，校验当前日期:<{}>是否大于生效日期:<{}>", currentDate, marketingAdsInfo.getBeginTime());
            return DateUtil.compareDate(marketingAdsInfo.getBeginTime(), currentDate) <= 0;
        } else {
            String currentDate = DateUtil.getCurrentDate();
            rglog.debug("生效日期不为空，失效日期不为空，校验当前日期:<{}>是否大于等于生效日期:<{}>并且小于等于失效日期:<{}>",
                    currentDate, marketingAdsInfo.getBeginTime(), marketingAdsInfo.getExpireTime());
            return (DateUtil.compareDate(currentDate, marketingAdsInfo.getBeginTime()) >= 0) && (DateUtil.compareDate(marketingAdsInfo.getExpireTime(), currentDate) >= 0);
        }
    }
}
